﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LogCommon;

namespace ServerTest
{
    public class ServerControl
    {
        private Socket serverSocket;
        private List<Socket> socketList;
        public ServerControl()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketList = new List<Socket>();
        }

        public void Start()
        {
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12321));
            serverSocket.Listen(10);
            Console.WriteLine(@"服务端已经启动开始侦听端口：12321");
            var task = Task.Run((Action) AcceptInfo);
            Task failTask = task.ContinueWith(t =>
            {
                t.Exception.Handle(e =>
                {
                    LogHelper.Fatal(e.Message);
                    return true;
                });
            },TaskContinuationOptions.OnlyOnFaulted);
            failTask.Wait();
        }

        private void AcceptInfo()
        {
            var client = serverSocket.Accept();
            var address = client.RemoteEndPoint as IPEndPoint;
            var ip = address.Address.ToString();
            var ips = address.AddressFamily.ToString();
            var port = address.Port;
            Console.WriteLine($@"{ips}-{ip}:{port}成功连接上本服务器");
            socketList.Add(client);
            var task = Task.Run(() => ReciveInfo(client));
            AcceptInfo();
            try
            {
                task.Wait();
            }
            catch (Exception e)
            {
                socketList.Remove(client);
                LogHelper.Fatal(e.Message);
            }
            

        }

        /// <summary>
        /// 接收消息
        /// </summary>
        private void ReciveInfo(object obj)
        {
            var client = obj as Socket;
            IPEndPoint point = client.RemoteEndPoint as IPEndPoint;
            try
            {
                byte[] msg = new byte[1024];
                var len = client.Receive(msg);
                string message = $"{point.Address}_{point.Port}:{Encoding.UTF8.GetString(msg, 0, len)}";
                Console.WriteLine(message);
                GuangBoInfo(client, message);
                //client.Send(Encoding.UTF8.GetBytes(@"服务器说：是的你说的对！"));
                ReciveInfo(client);
            }
            catch (Exception e)
            {
                Console.WriteLine($"{point.Address}_{point.Port}:我下线了。。。");
                LogHelper.Fatal(e.Message);
            }
            
        }

        private void GuangBoInfo(Socket outSocket, string msg)
        {
            foreach (var socket in socketList)
            {
                if(socket == outSocket) continue;
                socket.Send(Encoding.UTF8.GetBytes(msg));
            }
        }

    }
}
